package push.tools.service.framework.service;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import push.tools.service.framework.CryptoSupport;
import push.tools.service.utils.RandomCodeUtils;
import push.tools.service.utils.TimeUtils;
import push.tools.service.utils.crypto.SecretKeyPool;

import java.util.HashMap;

/**
 * 接口安全校验
 * "timestamp": 1697011200000,时间戳
 * "nonce": "a1b2c3d4e5f6",uuid
 * "signature": "f7d8e9c6a5b4f3e2d1c0b9a8f7e6d5c4",signature
 * "clientId": "web_app_v1",clientId
 * "version": "1.0"version
 */
@Service
public class SecurityRequestService extends CryptoSupport {
    private static final Logger logger = LoggerFactory.getLogger(SecurityRequestService.class);

    // 参数校验前处理
    public HashMap<String, String> preVerification(String requestBody) {
        HashMap<String, String> resMap = new HashMap<>();
        JSONObject jsonObject = (JSONObject) JSON.parse(requestBody);
        String timestamp = jsonObject.getString("timestamp");
        String nonce = jsonObject.getString("nonce");
        String signature = jsonObject.getString("signature");
        String clientId = jsonObject.getString("clientId");
        String version = jsonObject.getString("version");
        // 验证随机数
        HashMap<String, String> validateMap = RandomCodeUtils.validateUUID(nonce);
        if (!validateMap.get("state").equals("000")) {
            return validateMap;
        }
        // 验证时间戳（前后不超过2分钟）
        long timeDifference = TimeUtils.calculate(Long.parseLong(timestamp), System.currentTimeMillis());
        long limit = 1000 * 60 * 2;
        if (Math.abs(timeDifference) > limit) {
            resMap.put("state", "001");
            resMap.put("msg", "timestamp超时");
            return resMap;
        }
        // 验证其他参数
        if (clientId == null || clientId.isEmpty() || version == null || version.isEmpty()) {
            resMap.put("state", "002");
            resMap.put("msg", "版本号或客户端ID为空");
            return resMap;
        }
        // 根据版本号获取安全密钥
        String securityKey = SecretKeyPool.keyMap.get("security_request_key_v" + version);
        if (securityKey == null || securityKey.isEmpty()) {
            resMap.put("state", "003");
            resMap.put("msg", "版本号错误");
            return resMap;
        }
        // 签名按照一定的顺序->全小写再md5
        String s = nonce.toLowerCase() //
                + clientId.toLowerCase() //
                + version.toLowerCase()//
                + timestamp.toLowerCase()//
                + securityKey;
        String dynamicSignature = DigestUtils.md5Hex(s);
        if (signature == null || !signature.equals(dynamicSignature)) {
            resMap.put("state", "004");
            resMap.put("msg", "无效的签名");
            return resMap;
        }
        resMap.put("state", "000");
        resMap.put("msg", "校验通过");
        return resMap;
    }
}
